import { gql, useQuery, useMutation } from "@apollo/client"
import { message, Space, Card, Form } from "antd"
import { Link, useParams } from "react-router"
import { TextViewButton, TextDeleteButton } from "../../../../../components/BaseRoleButtonGroups"
import DelPopover from "../../../../../components/DelPopover"
import EditTable from "../../../../../components/EditTable"
import FormModal from "../../../../../components/FormModal"
import useOpen from "../../../../../hooks/useOpen"
import useRole from "../../../../../hooks/useRole"
import { useDataSource, useColumns } from "../../../../../hooks/useTable"
import gqlError from "../../../../../libs/gql-error"
import { BaseFields } from "../../../../../queries/base"
import { TestFields, TestEntity, TestChapterFields, TestChapterEntity } from "../../../../../queries/test"
import { QueryTestGroupByIdQuery, QueryTestGroupByIdResult } from "../page"
import { FormFactoryItem } from "../../../../../components/FormFactory"
import HeadBack from "../../../../../components/HeadBack"
[{
  type: "text",
  label: "PPT资源",
  name: "PPT",
}, {
  type: "text",
  label: "PDF资源",
  name: "PDF",
}, {
  type: "text",
  label: "视频资源",
  name: "video",
}, {
  type: "text",
  label: "一对一资源",
  name: "one2one",
}, {
  type: "text",
  label: "大纲资源",
  name: "outline",
}]
export const QueryTestByIdQuery = gql`
  query QueryTestById(
    $id: Int!
  ){
    queryTestById(
      id: $id
    ){
      ${BaseFields}
      ${TestFields}
    }
  }
`
export interface QueryTestByIdQuery {
  queryTestById: TestEntity
}

export const QueryTestChapterQuery = gql`
  query QueryTestChapter(
    $id: Int!
  ){
    queryTestChapters(
      id: $id
    ){
      ${BaseFields}
      ${TestChapterFields}
    }
  }
`
export interface QueryTestChapterResult {
  queryTestChapters: TestChapterEntity[]
}

const CreateTestChapterMutation = gql`
  mutation CreateTestChapter(
    $name: String!,
    $sys_testId: Int!,
    $money: Int,
    $is_test: Boolean,
    $desc: String,
    $order: Int,
    $status: Boolean,
    $PPT: String,
    $PDF: String,
    $video: String,
    $one2one: String,
    $outline: String
  ){
    createTestChapter(
      name: $name,
      sys_testId: $sys_testId,
      money: $money,
      is_test: $is_test,
      desc: $desc,
      order: $order,
      status: $status,
      PPT: $PPT,
      PDF: $PDF,
      video: $video,
      one2one: $one2one,
      outline: $outline
    ){
      id
    }
  }
`
const UpdateTestChapterMutation = gql`
  mutation UpdateTestChapter(
    $id: Int!,
    $name: String!,
    $money: Int,
    $is_test: Boolean,
    $desc: String,
    $order: Int,
    $status: Boolean,
    $PPT: String,
    $PDF: String,
    $video: String,
    $one2one: String,
    $outline: String
  ){
    updateTestChapter(
      id: $id,
      name: $name,
      money: $money,
      is_test: $is_test,
      desc: $desc,
      order: $order,
      status: $status,
      PPT: $PPT,
      PDF: $PDF,
      video: $video,
      one2one: $one2one,
      outline: $outline
    ){
      id
    }
  }
`
const DeleteTestChapterMutation = gql`
  mutation DeleteTestChapter(
    $id: Int!
  ){
    deleteTestChapter(
      id: $id
    ){
      id
    }
  }
`
const AdminTestGroupChapterPage = () => {

  const params = useParams()
  const groupId = parseInt(params.groupId || "0")
  const testId = parseInt(params.testId || "0")
  const group = useQuery<QueryTestGroupByIdResult>(QueryTestGroupByIdQuery, {
    variables: {
      id: groupId
    }
  })
  const test = useQuery<QueryTestByIdQuery>(QueryTestByIdQuery, {
    variables: {
      id: testId
    }
  })
  const { data, loading, refetch } = useQuery<QueryTestChapterResult>(QueryTestChapterQuery, {
    variables: {
      id: testId
    }
  })
  const [update, { loading: updateLoading }] = useMutation(UpdateTestChapterMutation, {
    onCompleted() {
      message.success("修改成功")
      refetch()
    },
    onError(error) {
      gqlError(error)
    },
  })
  const [del, { loading: deleteLoading }] = useMutation(DeleteTestChapterMutation, {
    onCompleted() {
      message.success(`删除成功`)
      refetch()
    },
    onError(error) {
      gqlError(error)
    },
  })
  const hasRole = useRole("/test")
  const dataSource = useDataSource([...(data?.queryTestChapters || [])]).sort((a, b) => a.order - b.order)
  const columns = useColumns([{
    title: "ID",
    dataIndex: "id"
  },
  {
    title: "名称",
    dataIndex: "name",
    type: "text"
  },
  {
    title: "状态",
    dataIndex: "status",
    type: "switch"
  },
  {
    title: "排序",
    dataIndex: "order",
    type: "number"
  },
  {
    title: "随机试题",
    dataIndex: "is_test",
    type: "switch"
  },
  {
    title: "价格",
    dataIndex: "money",
    type: "number"
  },
  {
    title: "描述",
    dataIndex: "desc",
    type: "text"
  },
  {
    title: "操作",
    render: (_: any, record: any) => {
      return (
        <Space>
          <Link to={`/admin/test/${groupId}/group/${testId}/chapter/${record.id}/paper`}>
            <TextViewButton />
          </Link>
          <DelPopover
            onDelete={() => {
              del({
                variables: {
                  id: record.id
                }
              })
            }}
          >
            <TextDeleteButton />
          </DelPopover>
        </Space>
      )
    }
  }])
  const [createForm] = Form.useForm()
  const [open, onOpen, onCancel] = useOpen()
  const CreateFormOptions: FormFactoryItem[] = [{
    type: "text",
    label: "名称",
    name: "name",
    rules: [{ required: true, message: "名称不能为空" }]
  }, {
    type: "number",
    label: "排序",
    name: "order",
  }, {
    type: "switch",
    label: "状态",
    name: "status",
    defaultValue: true
  }, {
    type: "switch",
    label: "随机试题",
    name: "is_test",
  }, {
    type: "number",
    label: "价格",
    name: "money",
  }, {
    type: "text",
    label: "描述",
    name: "desc",
  },]
  return (
    <Card>
      <HeadBack
        href={`/admin/test/${groupId}/group`}
      />
      <h1 className="text-2xl font-bold">
        {group.data?.queryTestGroupById.name} - {test.data?.queryTestById.name}
      </h1>
      <FormModal
        form={createForm}
        open={open}
        onCancel={onCancel}
        title="新增章节"
        query={CreateTestChapterMutation}
        options={CreateFormOptions}
        variables={{
          sys_testId: testId
        }}
        onCompleted={() => { refetch() }}
      />
      <EditTable
        dataSource={dataSource}
        loading={
          loading || updateLoading || deleteLoading
        }
        columns={columns}
        hasRole={hasRole}
        pagination={false}
        onCreate={onOpen}
        onChangeItem={(record, edit) => {
          update({
            variables: {
              ...record,
              ...edit
            }
          })
        }}
      />
    </Card>
  )
}
export default AdminTestGroupChapterPage